package com.fangshi.device

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.device.ScanDevice
import androidx.lifecycle.*
import kotlinx.coroutines.*

class HandheldScanner(
    private val context: Context,
    private val onScan: suspend (barcodeStr: String) -> Unit
) :
    Scanner() {

    private val scanAction = "scan.rcv.message"
    private val scanDevice: ScanDevice by lazy { ScanDevice() }
    private val job = SupervisorJob()

    private val scanEventReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (!intent.action.equals(scanAction)) {
                return
            }
            val barcode = intent.getByteArrayExtra("barocode")
            val barcodeLen = intent.getIntExtra("length", 0)
            val barcodeStr = String(barcode!!, 0, barcodeLen)
            CoroutineScope(Dispatchers.IO).launch {
                onScan(barcodeStr)
            }
        }
    }

    override fun startScan() {
        scanDevice.startScan()
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                val filter = IntentFilter()
                filter.addAction(scanAction)
                context.registerReceiver(scanEventReceiver, filter)
                scanDevice.openScan()
                scanDevice.outScanMode = 0
            }
            Lifecycle.Event.ON_DESTROY -> {
                context.unregisterReceiver(scanEventReceiver)
                scanDevice.stopScan()
                scanDevice.closeScan()
                scanDevice.scanLaserMode = 8
                job.cancel()
            }
            else -> {

            }
        }
    }
}